package fun.diaoer.service;

import java.util.ArrayList;
import java.util.List;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;
import fun.diaoer.common.Contants;
import fun.diaoer.entity.DISysPermission;
import fun.diaoer.entity.vo.VDISysRole;
import fun.diaoer.service.security.DiaoerUserDetail;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public abstract class AbstractService {
	
	/**
	 * 获取当前用户
	 */
	public String getUserId() {
		String userId = Contants.SYS_USER_ID;
		if (SecurityContextHolder.getContext() != null
				&& SecurityContextHolder.getContext().getAuthentication() != null) {
			Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
			if (principal instanceof UserDetails) {
				UserDetails userDetails = (UserDetails) principal;
				userId = userDetails.getUsername();
			}
		}
		return userId;
	}
	
	/**
	 * 获取当前用户角色名称
	 */
	public List<String> getRoleNmes() {
		List<String> roles=new ArrayList<>();
		if (SecurityContextHolder.getContext() != null
				&& SecurityContextHolder.getContext().getAuthentication() != null) {
			Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
			if (principal instanceof UserDetails) {
				UserDetails userDetails = (UserDetails) principal;
				for (GrantedAuthority g : userDetails.getAuthorities()) {
					roles.add(g.getAuthority());
				}
			}
		}
		return roles;
	}
	
	/**
	 * 获取当前用户角色
	 */
	public List<VDISysRole> getRoles() {
		List<VDISysRole> roles=null;
		if (SecurityContextHolder.getContext() != null
				&& SecurityContextHolder.getContext().getAuthentication() != null) {
			DiaoerUserDetail ud =  (DiaoerUserDetail) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
			roles=ud.getRoles();
		}
		return roles;
	}

	public List<DISysPermission> getPerms(){
		List<DISysPermission> perms=null;
		if (SecurityContextHolder.getContext() != null
				&& SecurityContextHolder.getContext().getAuthentication() != null) {
			DiaoerUserDetail ud= (DiaoerUserDetail) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
			perms=ud.getPerms();
		}
		return perms;
	}
	
	
}
